<template>
<div>
    <!-- 面包屑导航start -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
    <!-- 面包屑导航end -->

    <!-- 卡片区域start -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert  title="注意:只允许为第三级分类设置相关参数"  type="warning" :closable="false" show-icon> </el-alert>
              <el-row>
                  <el-col >
                      <span>选择商品分类:</span>
                      <el-cascader v-model="selectedkeys" :options="cateList" :props="panentprops" @change="panentChange" expand-trigger="hover" clearable>
                      </el-cascader>
                  </el-col>
              </el-row>
              <!--tas 页签start -->
                <el-tabs v-model="activeName" @tab-click="handleTasClick">
                    <el-tab-pane label="动态参数" name="many">
                        <el-button type="primary" size="mini" :disabled="idBtnDisabled" @click="paramDialogVisible=true">添加动态参数</el-button>
                        <!-- 动态参数表格start -->
                               <el-table  :data="manyTabData" stripe  border>
                                    <el-table-column type="expand" >
                                      <template v-slot="{row}">
                                        <!-- 渲染Tag标签 -->
                                        <el-tag v-for="(item , i) in row.attr_vals" :key="item.id" closable @close="handleClose(i,row)">{{item}}</el-tag>
                                        <!-- 输入的文本框 -->
                                           <el-input class="input-new-tag"  v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)"
                                          >
                                          </el-input>
                                          <!-- 添加按钮 -->
                                          <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
                                      </template>
                                    </el-table-column>
                                    <el-table-column type="index" label="#" ></el-table-column>
                                    <el-table-column prop="attr_name"  label="参数名称" ></el-table-column>
                                    <el-table-column  label="操作">
                                        <template v-slot="{row}">
                                            <!-- 修改 -->
                                        <el-button type="primary" icon="el-icon-edit" @click="showEaitDialog(row.attr_id)"></el-button>
                                            <!-- 删除 -->
                                        <el-button type="danger" icon="el-icon-delete" @click="removeParams(row.attr_id)" ></el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                        <!-- 动态参数表格end -->
                    </el-tab-pane>
                    <el-tab-pane label="静态属性" name="only">
                        <el-button type="primary" size="mini" :disabled="idBtnDisabled"  @click="paramDialogVisible=true">添加动态参数</el-button>
                         <!-- 静态参数表格start -->
                               <el-table  :data="onlyTabData" stripe  border>
                                    <el-table-column type="expand" >
                                      <template v-slot="{row}">
                                        <!-- 渲染Tag标签 -->
                                        <el-tag v-for="(item , i) in row.attr_vals" :key="item.id" closable @close="handleClose(i,row)">{{item}}</el-tag>
                                        <!-- 输入的文本框 -->
                                           <el-input class="input-new-tag"  v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)"
                                          >
                                          </el-input>
                                          <!-- 添加按钮 -->
                                          <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
                                      </template>
                                    </el-table-column>
                                    <el-table-column type="index" label="#" ></el-table-column>
                                    <el-table-column prop="attr_name"  label="参数名称" ></el-table-column>
                                    <el-table-column  label="操作">
                                        <template v-slot="{row}">
                                            <!-- 修改 -->
                                        <el-button type="primary" icon="el-icon-edit" @click="showEaitDialog(row.attr_id)" ></el-button>
                                            <!-- 删除 -->
                                        <el-button type="danger" icon="el-icon-delete" @click="removeParams(row.attr_id)"></el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                        <!-- 静态参数表格end -->
                    </el-tab-pane>
                </el-tabs>
             <!--tas 页签end -->
        </el-card>
    <!-- 卡片区域end -->

    <!-- 添加参数对话框start -->
            <el-dialog   :title="'添加'+TitleText"  :visible.sync="paramDialogVisible"   width="50%" @close="addColse" >
               <!-- 表格 -->
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="TitleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="paramDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addParams">确 定</el-button>
                </span>
                </el-dialog>
    <!-- 添加参数对话框end -->

    <!-- 修改参数对话框start -->
            <el-dialog   :title="'修改'+TitleText"  :visible.sync="eaitVisible"   width="50%" @close="eaitColse" >
               <!-- 表格 -->
                <el-form :model="eaitForm" :rules="eaitFormRules" ref="eaitFormRef" label-width="100px" >
                <el-form-item :label="TitleText" prop="attr_name">
                    <el-input v-model="eaitForm.attr_name"></el-input>
                </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="eaitVisible = false">取 消</el-button>
                    <el-button type="primary" @click="eaitParams">确 定</el-button>
                </span>
                </el-dialog>
    <!-- 修改参数对话框end -->

</div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      selectedkeys: [],
      panentprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   被激活的页签
      activeName: 'many',
      manyTabData: [],
      onlyTabData: [],
      paramDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 显示与隐藏修改按钮
      eaitVisible: false,
      // 修改参数列表
      eaitForm: {
        attr_name: ''
      },
      // 修改参数校验
      eaitFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类数据列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.cateList = res.data
    },
    panentChange () {
      this.getparamsList()
    },
    handleTasClick () {
      this.getparamsList()
      console.log(this.activeName)
    },
    // 获取参数列表的数据
    async getparamsList () {
      if (this.selectedkeys.length !== 3) {
        this.selectedkeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    addColse () {
      this.$refs.addFormRef.resetFields()
    },
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.paramDialogVisible = false
        this.getparamsList()
      })
    },
    // 点击按钮显示与隐藏修改按钮
    async showEaitDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.eaitForm = res.data
      this.eaitVisible = true
    },
    // 点击确定按钮提交修改操作
    eaitParams () {
      this.$refs.eaitFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.eaitForm.attr_id}`, {
          attr_name: this.eaitForm.attr_name, attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getparamsList()
        this.eaitVisible = false
      })
    },
    // 监听修改对话框关闭重置事件
    eaitColse () {
      this.$refs.eaitFormRef.resetFields()
    },
    // 根据ID删除对应参数项
    async removeParams (id) {
      const removeUser = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeUser !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getparamsList()
    },
    // 文本框输入或按下enter键触发事件
    async  handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      // 需要发起请求保存这次操作
      this.saveAttrvals(row)
    },
    // 点击按钮让文本框显示
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 将attr_vals 操作保存到数据库
    async saveAttrvals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    },
    // 删除参数可选项
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrvals(row)
    }
  },

  computed: {
    idBtnDisabled () {
      if (this.selectedkeys.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectedkeys.length === 3) {
        return this.selectedkeys[2]
      }
      return null
    },
    // 计算动态参数与静态属性的标题
    TitleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert{
    margin-bottom: 10px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>
